package com.ulife.order.components.core.refund;

import com.ulife.base.entities.order.SoRefundBill;
import com.ulife.common.utils.lang.SpringContextHolder;
import com.ulife.order.api.core.refund.Channels;
import com.ulife.order.api.core.refund.RefundStatus;
import com.ulife.order.components.core.refund.factory.AutoRefundFactory;
import com.ulife.order.components.core.refund.factory.BalanceRefundFactory;
import com.ulife.order.components.core.refund.factory.DefaultRefundFactory;
import com.ulife.order.components.core.refund.factory.IRefundFactory;
import com.ulife.order.components.core.result.BaseResult;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lbq on 2016/05/26.
 */
public class RefundManager {
    /*
    * 根据退款单据获取退款处理方式
    * 步骤
    * 1.验证退款单据
    * 2.处理退款，返回退款结果
    * 3.根据退款渠道和退款路径确定退款方式
    * */
    private static RefundManager instance;

    private static Map<String,IRefundFactory> channelsRefundFactoryMap;
    private static IRefundFactory defaultRefundFactory;
    private RefundManager() throws Exception {
        init();
    }
    public static RefundManager getInstance() throws Exception {
        if (instance == null){
            synchronized (RefundManager.class) {
                if (instance == null) {
                    instance = new RefundManager();
                }
            }
        }
        return instance;
    }

    private void init() throws Exception {
        try {
            //初始化 退款渠道和退款方法的对应关系
            defaultRefundFactory = SpringContextHolder.getBean("defaultRefundFactory");
            channelsRefundFactoryMap = new HashMap<String,IRefundFactory>();
            channelsRefundFactoryMap.put(Channels.Alipay.value(), SpringContextHolder.getBean("autoRefundFactory"));
            channelsRefundFactoryMap.put(Channels.WeiXin.value(),SpringContextHolder.getBean("autoRefundFactory"));
            channelsRefundFactoryMap.put(Channels.Balance.value(),SpringContextHolder.getBean("balanceRefundFactory"));
        } catch (Exception ex) {
            throw new Exception("退款管理器初始化失败，错误信息：" + ex.getMessage());
        }
    }
    /**
     * 获取退款方式
     * @return
     */
    public IRefundFactory getRefundFactory(String refundChannel) {

        if (!channelsRefundFactoryMap.containsKey(refundChannel)) {
            return defaultRefundFactory;
        }
        return channelsRefundFactoryMap.get(refundChannel);
    }

    /**
     * 退款结果 -1 退款失败，1 退款成功
     * @param soRefundBill
     * @return
     */
    public BaseResult<RefundStatus> processRefund(SoRefundBill soRefundBill,long operator){
        IRefundFactory refundFactory = getRefundFactory(soRefundBill.getRefundChannel());
        return refundFactory.processRefund(soRefundBill,operator);
    }
}
